import { useState, useEffect, useCallback } from 'react';

export const useChromeStorageObject = (key, defaultValue = {}) => {
  const [value, setValue] = useState(defaultValue);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    chrome.storage.local.get([key], (result) => {
      if (chrome.runtime.lastError) {
        console.error('Error reading storage:', chrome.runtime.lastError);
        setValue(defaultValue);
      } else {
        setValue(result[key] || defaultValue);
      }
      setLoading(false);
    });
  }, [key, defaultValue]);

  const updateValue = useCallback((updates) => {
    const newValue = { ...value, ...updates };
    setValue(newValue);
    chrome.storage.local.set({ [key]: newValue }, () => {
      if (chrome.runtime.lastError) {
        console.error('Error writing storage:', chrome.runtime.lastError);
      }
    });
  }, [key, value]);

  return [value, updateValue, loading];
};

